package com.zbowen.way.service;

import com.zbowen.way.config.AppConfig;
import com.zbowen.way.utils.ResultUtils;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.util.Timeout;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpClientService {

    public static void main(String[] args) throws IOException, ParseException {
        // 获取默认配置的 HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //  创建请求配置信息
        RequestConfig  requestConfig = RequestConfig.custom()
                // 设置连接超时时间
                .setConnectTimeout(Timeout.of(3000, TimeUnit.MILLISECONDS))
                // 设置响应超时时间
                .setResponseTimeout(3000, TimeUnit.MILLISECONDS)
                // 设置从连接池获取链接的超时时间
                .setConnectionRequestTimeout(3000, TimeUnit.MILLISECONDS)
                .build();

        // 起点经纬度 牛湾新村
        String origin = "113.854637,22.580915";
        // 终点经纬度 豪威科技大厦
        String destination = "113.95249,22.533516";

        Map<String, String> params = new HashMap<>();
        params.put("key", AppConfig.key);
        params.put("origin", origin);
        params.put("destination", destination);
        params.put("strategy", "34");
        params.put("plate", "粤BGB2887");
        params.put("cartype", "2");
        params.put("show_fields", "cost,tmcs,navi,polyline");

        StringBuilder sb = new StringBuilder();
        sb.append(AppConfig.url_2).append("?1=1");
        params.forEach((key, value) -> {
            sb.append("&").append(key).append("=").append(value);
        });

        // 创建 GET 请求对象
        HttpGet httpGet = new HttpGet(sb.toString());
        // 设置请求参数
        httpGet.setConfig(requestConfig);
        // 发起请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 获取请求状态
        int code = response.getCode();
        if (code == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            ResultUtils.print(result);
        }

    }
}
